package com.file.service.impl;

import com.aliyun.oss.OSSClient;
import com.aliyun.oss.model.*;
import com.file.exceptions.ExceptionEnum;
import com.file.exceptions.ServiceException;
import com.file.utils.ConfigHelper;
import com.file.utils.StaticConstant;
import org.apache.log4j.Logger;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by chairal on 2017/7/21.
 */
@Service
public class TaskServiceImpl {
    static final Logger logger = Logger.getLogger(TaskServiceImpl.class);

    @Autowired
    ConfigHelper configHelper;

    /**
     * 定时删除临时图片
     */
    @Scheduled(cron = "0 0 3 * * ? ")
    public void delTempImgTask() {
        logger.info("=============定时删除临时图片 start=============");
        logger.info("开始时间："+ DateTime.now().toString("yyyy-MM-dd HH:mm:ss.SSS"));
        String endpoint = StaticConstant.endpoint;
        String accessKeyId = StaticConstant.accessKeyId;
        String accessKeySecret = StaticConstant.accessKeySecret;
        String bucketName = StaticConstant.bucketName;
        logger.info("endpoint："+ endpoint);
        logger.info("accessKeyId："+ accessKeyId);
        logger.info("accessKeySecret："+ accessKeySecret);
        logger.info("bucketName："+ bucketName);
        //日期
        String date = DateTime.now().plusDays(-5).toString("yyyyMMdd");
        //图片前缀路径
        String ossImgMapPath = configHelper.getOssImgMapPath();
        String[] folders = new String[1];
        folders[0] = ossImgMapPath + StaticConstant.SEPARATOR + "temp" + StaticConstant.SEPARATOR + "league"
                + StaticConstant.SEPARATOR + "contest" + StaticConstant.SEPARATOR + date;
        OSSClient ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);
        try {
            // 构造ListObjectsRequest请求
            ListObjectsRequest listObjectsRequest = new ListObjectsRequest(bucketName);
            //"/"为文件夹的分隔符
    //        listObjectsRequest.setDelimiter("/");
            for (String path : folders) {
                //列出目录下的所有文件
                listObjectsRequest.setPrefix(path + StaticConstant.SEPARATOR);
                logger.info("要列出的文件前缀：" + path + StaticConstant.SEPARATOR);
                //object最大1000个，要分页显示所有
                final int maxKeys = 1000;
                String nextMarker = null;
                ObjectListing objectListing = null;
                //待删除的key集合
                List<String> keys = new ArrayList<String>();
                do {
                    objectListing = ossClient.listObjects(listObjectsRequest.withMarker(nextMarker)
                            .withMaxKeys(maxKeys));
                    List<OSSObjectSummary> sums = objectListing.getObjectSummaries();
                    for (OSSObjectSummary s : sums) {
                        keys.add(s.getKey());
                    }
                    nextMarker = objectListing.getNextMarker();
                } while (objectListing.isTruncated());
                DeleteObjectsRequest deleteObjectsRequest = new DeleteObjectsRequest(bucketName);
                if(!CollectionUtils.isEmpty(keys)){
                    deleteObjectsRequest.withKeys(keys);
                    //删除oss上的图片文件
                    DeleteObjectsResult deleteObjectsResult = ossClient.deleteObjects(deleteObjectsRequest);
                }
            }
            logger.info("结束时间："+ DateTime.now().toString("yyyy-MM-dd HH:mm:ss.SSS"));
            logger.info("=============定时删除临时图片 end=============");
        } catch (Exception e) {
            logger.error(e.getMessage());
            throw new ServiceException(ExceptionEnum.IMAGE_UPLOAD_FAIL);
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
    }

}
